package com.elsa.auth.controller;

import java.security.Principal;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.oauth2.provider.token.ConsumerTokenServices;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import com.elsa.common.entity.ElsaResponse;
import com.elsa.common.exception.ElsaAuthException;

/**
 * @projectName：elsa-auth
 * @typeName：SecurityController
 * @author：cos
 * @date：2021年5月7日
 * @version
 * @desc：对外提供一些REST服务
 */
@RestController
public class SecurityController {
	@Autowired
    private ConsumerTokenServices consumerTokenServices;

    @GetMapping("oauth/test")
    public String testOauth() {
        return "oauth";
    }

    @GetMapping("user")
    public Principal currentUser(Principal principal) {
        return principal;
    }

    @DeleteMapping("signout")
    public ElsaResponse signout(HttpServletRequest request) throws ElsaAuthException {
        String authorization = request.getHeader("Authorization");
        String token = StringUtils.replace(authorization, "bearer ", "");
        ElsaResponse elsaResponse = new ElsaResponse();
        if (!consumerTokenServices.revokeToken(token)) {
            throw new ElsaAuthException("退出登录失败");
        }
        return elsaResponse.message("退出登录成功");
    }
}
